<template>
  <section v-if="isShow" class="page full-page">
    <section class="full-page bg-default">
      <div class="video-wrap full-page bg-black" :id="'videoPlayer_'+selfIndex">
        <cube-slide
          :threshold="0.1"
          :showDots="false"
          :autoPlay="false"
          :direction="'vertical'"
          :loop="false"
          :style="{ width: '100vw' }"
          ref="slide"
          :data="list"
          @change="changePage"
        >
          <fetchData :loading="isLoading" :data="list"></fetchData>
          <cube-slide-item
            :style="{ width: '100vw' }"
            v-for="(item, idx) in list"
            :key="'item' + currentVideoIndex + idx"
          >
            <videoItem
              :ref="'videoItem_'+selfIndex +'_'+idx"
              :key="'item' + currentVideoIndex + idx"
              @onplay="onplay"
              @ended="ended"
              @focus="focus"
              :focusTime="focusTime"
              :currentVideoIndex="currentVideoIndex"
              :data="item"
              :index="idx"
              :videoPlayerIndex="selfIndex"
              :currentVideoPlayerIndex="currentIndex"
              :isDormancy="isDormancy"
            ></videoItem>
          </cube-slide-item>
          <noData v-if="!isLoading && list.length === 0"></noData>
        </cube-slide>
      </div>
    </section>
    <readScore
      ref="scoreInstance"
      :_contentId="currentContentId"
      :type="2"
    ></readScore>
  </section>
</template>


<script>
import likeUpsComponent from "@/components/common/likeUpsComponent.vue";
import videoItem from "../video/videoItem.vue";
import StorageKeys from "@/common/const/StorageKeys";
import $ from "../../../../../static/js/jquery-1.12.4.min";
export default {
  components: { likeUpsComponent, videoItem },
  name: "playerOne",
  props: ["menuId","selfIndex","currentIndex"],
  data() {
    return {
      isShow: !true,
      isFullScreen: false,
      list: [], //视频数据列表
      currentContentId: "",
      currentVideoIndex: 0,
      pageIndex: 1,
      pageSize: 6,
      recommendPageSize:50, //推荐播客分页大小
      focusTime: 30,
      detail: {},
      userInfo: {}, //用户信息
      isLoading: true,
      isDormancy: true, //是否休眠，目前只有playerOne.vue用到
      fromType: '', //推荐页是从置顶视频进来还是更多进来
      isEnd: false, //判断是否到底没有数据了
    };
  },
  watch: {
    currentIndex(newVal, oldVal) {
      if (newVal != this.selfIndex) {
        console.log("需停止音频的tab", this.selfIndex);
        this.isDormancy = true;
      } else {
        console.log("当前活跃的tab", this.selfIndex);
        this.isDormancy = false;
      }
    },
  },
  created() {
    this.isShow = true;
    // window.audioPlayer.pause();
    this.userInfo = this.$localStorage.get("userInfo");
  },
  mounted() {
    this.$nextTick(()=>{
      this.init();
       //是否休眠
      if (this.currentIndex == this.selfIndex) {
          this.isDormancy =  false;
      }else{
          this.isDormancy =  true;
      }
      this.$route.meta.keepAlive = true;
      this.$store.commit('addRoute','podcast')
    })
  },
  activated(){
    if (this.list.length<1) { //没数据时刷新数据
      this.init();
    }
  },
  beforeDestroy() {
    // this.onback();
  },
  beforeRouteLeave(to, from, next) {
    this.$refs.scoreInstance.stopRead();
    if (window.douyinCommentInstance) {
      window.douyinCommentInstance.back();
    }
    next();
  },
  beforeRouteEnter(to, from, next) {
    console.log("beforeRouteEnter");
    next();
  },
  methods: {
    // 初始化
    init() {
      this.isEnd = false; //初始化时，未到底
      this.$store.state.isVideo = true;
      this.tools.stopAudio();
      this.pageIndex = 1;
      this.list = [];
      this.currentVideoIndex = 0;
      this.$nextTick(()=>{
        if(this.selfIndex === 2) { // 推荐
          this.fromType = this.$store.state.currentTopData.fromType;
          if (this.fromType == 'top') {
            this.list = this.getDataByStorageKey(StorageKeys.HOME_VIDEO_LIST) || [];
            this.currentVideoIndex = this.$store.state.currentTopData.index;
          }
        }
        if (!this.isEnd) {
          this.fetchList();
        }
      })
    },
    /*获取缓存数据*/
    getDataByStorageKey(key) {
      let _list = this.$localStorage.get(key);
      if (_list && Array.isArray(_list) && _list.length > 0) {
        return _list;
      }
      return false;
    },
    // 请求列表数据
    fetchList() {
      if (this.selfIndex === 1) { // 获取所有关注者的最新视频
        this.play_myWatched();
      }else if(this.selfIndex === 2) { // 请求红云播客推荐分页数据
        this.play_recommendPage();
      }else{ // 活动数据
        this.play_getContentByActivity(this.menuId);
      }
    },
    // 获取所有关注者的最新视频
    play_myWatched() {
      this.isEnd = false;
      this.isLoading = true;
      let data = {
	      userId: this.userInfo.id,
        pageNo: this.pageIndex + "",
        pageSize: this.pageSize,
      };
      return this.fetchService.play_myWatched(data).then((res) => {
        this.isLoading = false;
        if (res.code !== 0) {
          return this.tools.alert(
            res.message || res.resp_msg || "接口出错，请联系管理员"
          );
        }
        if (this.pageIndex === 1) {
          this.detail = res.data[0];
        }

        if (res.data.length<this.pageSize) {
          this.isEnd = true; //到底了,不要再请求
        }

        this.list = this.list.concat(res.data);
        this.pageIndex++;

        // 跳转到对应视频
        this.viewVideo(this.currentVideoIndex);
      });
    },
    // 请求红云播客推荐分页数据
    play_recommendPage() {
      this.isEnd = false;
      this.isLoading = true;
      let data = {
        excludeIds: this.$store.state.douyinExcludeIds,
        dgwName: "",
        pageNo: this.pageIndex + "",
        pageSize: this.recommendPageSize,
        title: "",
        yearMonth: ""
      };
      return this.fetchService.play_recommendPage(data).then((res) => {
        this.isLoading = false;
        if (res.code !== 0) {
          return this.tools.alert(
            res.message || res.resp_msg || "接口出错，请联系管理员"
          );
        }
        if (this.pageIndex === 1) {
          this.detail = res.data[0];
        }

        if (res.data.length<this.recommendPageSize) {
          this.isEnd = true; //到底了,不要再请求
        }

        this.list = this.list.concat(res.data);
        this.pageIndex++;

        // 跳转到对应视频
        this.viewVideo(this.currentVideoIndex);
      });
    },
    // 获取活动内容分页数据
    play_getContentByActivity(id) {
      this.isEnd = false;
      this.isLoading = true;
      let data = {
        activityId: id,
        pageNo: this.pageIndex + "",
        pageSize: this.pageSize,
      };
      return this.fetchService.play_getContentByActivity(data).then((res) => {
        this.isLoading = false;
        if (res.code !== 0) {
          return this.tools.alert(
            res.message || res.resp_msg || "接口出错，请联系管理员"
          );
        }
        if (this.pageIndex === 1) {
          this.detail = res.data[0];
        }

        if (res.data.length<this.pageSize) {
          this.isEnd = true; //到底了,不要再请求
        }

        this.list = this.list.concat(res.data);
        this.pageIndex++;

        // 跳转到对应视频
        this.viewVideo(this.currentVideoIndex);
      });
    },
    // 跳转到对应视频
    viewVideo(index) {
      setTimeout(() => {
        if (this.$refs.slide) {
          this.$refs.slide.slide.goToPage(0, index, 1); // 第三个参数设置为0时，第2个视频往上翻无法触发翻页事件
          console.log(`标签${this.selfIndex},当前播放标签${this.currentIndex},切换视频${index}完成`)
        }
      }, 0);
    },
    focus() {
      this.focusTime = Date.now();
    },
    play(e) {
      e.target.play();
    },
    // 播放时
    onplay(e) {
      this.addScore(this.currentVideoIndex);
    },
    /*视频播放结束时触发*/
    ended() {
      this.$refs.scoreInstance.getScore("watch");
    },
    /*添加积分*/
    addScore(index) {
      let len = this.list.length;
      if (index >= len) {
        index = len - 1;
      }
      let content = this.list[index];
      console.log("video content", content);
      this.currentContentId = content.id;
      this.$nextTick(() => {
        this.$refs.scoreInstance.startRead();
      });
    },
    // 返回时
    /* onback() {
      $(".video-player-item").attr('id','videoItem_pause');
      let videos = document.querySelectorAll("video");
      for (let i = 0; i < videos.length; i++) {
        videos[i].pause();
        setTimeout(() => {
          videos[i].remove();
        }, 50);
      }
    }, */
    // 翻页
    changePage(currIndex) {
      if (this.list.length - currIndex < 3 && !this.isEnd) {
        this.fetchList();
      }
      this.currentVideoIndex = currIndex;
      console.log("当前轮播图序号为:" + currIndex);
      this.playVideo(currIndex);
      if (this.list.length == currIndex + 1 && this.isEnd) {
        this.tools.tip('最后一条视频');
      }
    },
    // 播放视频
    playVideo(index) {
      let videos = document.querySelectorAll("video");
      if (videos.length < 1) {
        return false;
      }
      for (let i = 0; i < videos.length; i++) {
        // videoItem.vue组件，beforeDestroy已销毁player
        // let _vueNode = this.$refs['videoItem_'+this.selfIndex +'_'+i];
        // if (_vueNode) _vueNode[0].pause();
      }
      if (index >= videos.length) {
        this.$store.state.newsDetail = this.detail = this.list[index - 1];
        index = videos.length - 1;
      }
      let _vueNode = this.$refs['videoItem_'+this.selfIndex +'_'+index];
      if (_vueNode) _vueNode[0].play();
    },
    // 过滤掉首页那几个视频
    excludeIds(list, arrExcludeIds) {
      let ret = [];
      if (!arrExcludeIds) {
        return list;
      }
      list.forEach((v) => {
        if (!arrExcludeIds.includes(v.id)) {
          ret.push(v);
        }
      });
      return ret;
    },
  },
};
</script>


<style scoped lang="scss">
@import "@/common/stylus/moon.scss";
*::-webkit-media-controls-start-playback-button {
  display: block;
  -webkit-appearance: block;
}
*::-webkit-media-controls-panel {
  display: block;
  -webkit-appearance: block;
}

*::--webkit-media-controls-play-button {
  display: block;
  -webkit-appearance: block;
}
.video {
  video {
    /*opacity: 0;*/
  }
  .poster {
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: 3;
    overflow: hidden;
    background-color: $theme-color;
    img {
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 100%;
      height: auto;
    }
  }
  .self {
    position: relative;
    z-index: 1;
    width: 100%;
    height: 100%;
    .left-bar {
      position: absolute;
    }
  }
}
.full-page {
  padding: 0;
  height: 100vh;
  .head-wrap,
  .top-menu,
  .btn-menu {
    display: none;
  }
  .cube-slide-group,
  .cube-slide-item,
  .video {
    height: 100vh !important;
  }
}
.video-wrap .video .video-title {
  width: 70%;
}
</style>

